package com.hsnn.medstgmini.sys.controller;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hsnn.medstgmini.Constants;
import com.hsnn.medstgmini.base.std.model.HospInfo;
import com.hsnn.medstgmini.base.std.model.StdCompinfo;
import com.hsnn.medstgmini.base.std.model.StdExpert;
import com.hsnn.medstgmini.base.std.model.StdHealthbureau;
import com.hsnn.medstgmini.base.std.service.StdCompinfoManager;
import com.hsnn.medstgmini.base.std.service.StdExpertManager;
import com.hsnn.medstgmini.base.std.service.StdHospInfoManager;
import com.hsnn.medstgmini.exception.MSException;
import com.hsnn.medstgmini.model.Whether;
import com.hsnn.medstgmini.pro.project.service.BidProjAreaManager;
import com.hsnn.medstgmini.settlement.service.SetPaynoticeManager;
import com.hsnn.medstgmini.sys.model.SysPrivilege;
import com.hsnn.medstgmini.sys.model.SysRole;
import com.hsnn.medstgmini.sys.model.SysRoleType;
import com.hsnn.medstgmini.sys.model.SysUser;
import com.hsnn.medstgmini.sys.model.UserType;
import com.hsnn.medstgmini.sys.service.SysRoleManager;
import com.hsnn.medstgmini.sys.service.SysUserManager;
import com.hsnn.medstgmini.util.AccountUtil;
import com.hsnn.medstgmini.util.AreaUtil;
import com.hsnn.medstgmini.util.BeanCopierUtils;
import com.hsnn.medstgmini.util.DbUtil;
import com.hsnn.medstgmini.util.Pagination;
import com.hsnn.medstgmini.util.ParseNumber;

/**
 * @category 用户
 * @author 蔡春龙
 * @date 2015年6月16日
 */
@Controller
@RequestMapping("/sysUser")
public class SysUserController {

	private static final Logger log = Logger.getLogger(SysUserController.class);

	@Autowired
	private SysUserManager userManager;

	@Autowired
	private SysRoleManager roleManager;

	@Autowired
	private StdHospInfoManager hospInfoManager;

	@Autowired
	private StdCompinfoManager compinfoManager;

	@Autowired
	private StdExpertManager expertManager;

	@Autowired
	private HttpServletRequest request;

	@Autowired
	private StdHospInfoManager stdHospInfoManager;
	
	@Autowired
	private StdCompinfoManager stdCompinfoManager;
	
	@Autowired
	private StdExpertManager stdExpertManager;
	
	@Autowired
	private SetPaynoticeManager setPaynoticeManager;
	
	@Autowired
	private BidProjAreaManager bidProjAreaManager;
	
	@Autowired
	private HttpSession session;
	
	@Value("#{sysProp['main.leixing.yiju']}")
	private String businessGist;
	
	@Value("#{sysProp['username.login.address']}")
	private String url;
	/**
	 * @category 获取当前登陆人信息
	 * @date 2015年6月14日
	 * @return
	 */
	private SysUser getUser() {
		return (SysUser) session.getAttribute(Constants.USERINFO);
	}

	/**
	 * @category 中心用户管理列表页面
	 * @date 2015年6月18日
	 * @param model
	 * @return
	 */
	@RequestMapping("/zxUserList")
	public String zxUserList(Model model) {
		log.info("enter zxUserList method");
		List<UserType> userTypeList = new ArrayList<UserType>();
		for (UserType userType : UserType.values()) {
			if (userType.getKey() != 1) {
				userTypeList.add(userType);
			}
		}
		model.addAttribute("userTypeList", userTypeList);
		return "/sys/zxUserList";
	}

	/**
	 * @category 中心查询主用户列表
	 * @date 2015年6月18日
	 * @param user
	 * @return
	 */
	@RequestMapping("/getZxUserList")
	@ResponseBody
	public Pagination getZxUserList(SysUser user) {
		log.info(user.toString());
		Pagination page = new Pagination(request);
		try {
			DbUtil.jsonToMap(request, page);
			userManager.getZxUserList(page, user);
			page.setSuccess(true);
		} catch (Exception e) {
			log.error("",e);
			page.setSuccess(false);
		}
		return page;
	}

	/**
	 * @category 启用|停用
	 * @param user
	 * @return
	 */
	@RequestMapping("changeStatus")
	@ResponseBody
	public Pagination changeStatus(SysUser user) {
		log.info(user.toString());
		Pagination page = new Pagination();
		try {
			if (user != null && user.getId() != null) {
				user.setUpdUser(getUser().getId());
				user.setUpdDateTime(new Date());
				userManager.changeStatus(user);
				page.setSuccess(true);
			}
		} catch (Exception e) {
			log.error("",e);
			page.setSuccess(false);
		}
		return page;
	}

	/**
	 * @category 批量(启用|停用)
	 * @param array
	 * @return
	 */
	@RequestMapping(value={"enable","disable","subEnable","subDisable"})
	@ResponseBody
	public Pagination batchChangeStatus(String param,String state) {
		log.info("param="+param+",state="+state);
		Pagination page = new Pagination();
		int status = ParseNumber.toInteger(state);
		String updUserId = getUser().getId();
		try {
				String[] ids = request.getParameter("param").split(",");
				List<SysUser> list =new ArrayList<SysUser>();
				if(ids.length>0){
					for(int i = 0;i<ids.length;i++){
						if(Whether.no.getKey()==status){
							//根据主用户id查是否有子用户;主用户停用后，旗下子用户也要停用
							List<String> subList =userManager.getSubUserByzxId(ids[i]); 
							if(subList!=null){
								for(String subId : subList){
									SysUser su = new SysUser();
									su.setStatus(status);
									su.setId(subId);
									su.setUpdUser(updUserId);
									su.setUpdDateTime(new Date());
									list.add(su);
								}
							}
						}
						SysUser su = new SysUser();
						su.setStatus(ParseNumber.toInteger(state));
						su.setId(ids[i]);
						su.setUpdUser(updUserId);
						su.setUpdDateTime(new Date());
						list.add(su);
					}
					userManager.batchChangeStatus(list);
					page.setSuccess(true);
				}
		} catch (Exception e) {
			log.error("",e);
			page.setSuccess(false);
		}
		return page;
	}

	/**
	 * @category 中心跳转医疗机构、生产企业、配送企业信息选择页面
	 * @date 2015年6月14日
	 * @return
	 */
	@RequestMapping("/zxUserSelected")
	public String zxUserSelected(Model model, int userType) {
		log.info("userType="+userType);
		model.addAttribute("userType", userType);
		if (UserType.yy.getKey() == userType) {
			return "/sys/yySelect";
		} else if (UserType.sc.getKey() == userType || UserType.ps.getKey() == userType) {
			return "/sys/qySelected";
		} else if (UserType.zj.getKey() == userType) {
			List<Object> expSkillsList =userManager.getExpSkillsList();
			model.addAttribute("expSkillsList", expSkillsList);
			return "/sys/zjSelected";
		} else if (UserType.hszx.getKey() == userType) {
			return "/sys/hszxSelected";
		}
		
		return "/404";
	}
	
	/**
	 * @category 医疗机构、生产企业、配送企业、专家、卫生局生成账号弹窗
	 * @date 2015年6月14日
	 * @return
	 * @throws UnsupportedEncodingException 
	 */
	@RequestMapping("/toGenerateAccount")
	public String toGenerateAccount(Model model,String id,String userType,String name) throws UnsupportedEncodingException {
		log.info("userType="+userType+",id="+id+",name="+name);
		String zhuRole=SysRoleType.getSysRoleType(ParseNumber.toInteger(userType)).getValue();
		List<SysRole> sysRoles = userManager.getSysRoleListByType(zhuRole);
		int checkGenerateSubAccount =Whether.no.getKey();
		if(sysRoles!=null && sysRoles.size()>0){
			checkGenerateSubAccount=Whether.yes.getKey();
		}
		String compName = new String(name.getBytes("ISO-8859-1"),"UTF-8");
		model.addAttribute("checkGenerateSubAccount", checkGenerateSubAccount);
		model.addAttribute("businessGist", businessGist);
		model.addAttribute("id", id);
		model.addAttribute("name", compName);
		model.addAttribute("userType", userType);
		return "/sys/generateAccount";
	}
	

	/**
	 * @category 生成账号
	 * @author 应晓川
	 * @date 2015年10月17日13:38:17
	 * @param 
	 * @return
	 */
	@RequestMapping("generateSubAccount")
	@ResponseBody
	public Pagination generateSubAccount(String id,Integer userType,String bussinessShow,Integer generateSubAccount) {
		log.info("机构id="+id+",userType="+userType+",bussinessShow="+bussinessShow+",generateSubAccount="+generateSubAccount);
		Pagination page = new Pagination();
		if(userType == UserType.yy.getKey()){
			return getYYUserName(id,userType,bussinessShow);
		}else{
			SysUser  su= new SysUser();
			String zhuId = UUID.randomUUID().toString();
			String zhuSequence = AccountUtil.getSequence(userType);//主用户账号
			String password = AccountUtil.getPassword(6);//主用户密码
			String createUserId = getUser().getId();
			List<HashMap<String,String>> list = new ArrayList<HashMap<String,String>>();
			Date  now= new Date();
			try {
				su.setId(zhuId);
				su.setOrgId(id);
				su.setUsername(zhuSequence);
				su.setPassword(DigestUtils.md5Hex(password));
				su.setAcctEnabled(Whether.yes.getKey());//激活账号
				su.setLocked(Whether.no.getKey());//不锁定账号
				su.setType(userType);//用户类型
				su.setMain(Whether.yes.getKey());//主账号
				if(StringUtils.isNotBlank(bussinessShow)){
					su.setBussinessShow(bussinessShow);//账号类型
				}
				su.setStatus(Whether.yes.getKey());
				su.setCreateUserId(createUserId);
				su.setCreateDateTime(now);
				switch (userType) {
				case Constants.SC:case Constants.PS:
					StdCompinfo stdCompinfo = stdCompinfoManager.queryStdCompInfoByCompId(id);
					su.setName(stdCompinfo.getCompName());
					su.setPhone(stdCompinfo.getCompPhone());
					break;
				case Constants.YY:
					HospInfo hospInfo = stdHospInfoManager.getHospInfoById(id);
					su.setName(hospInfo.getHospName());
					su.setPhone(hospInfo.getHospPhone());
					break;
				case Constants.ZJ:
					 StdExpert stdExpert= stdExpertManager.getStdExpertById(id);
					 su.setName(stdExpert.getName());
					 su.setPhone(stdExpert.getCompPhone());
					break;
				case Constants.HSZX:
					StdHealthbureau stdHealthbureau= setPaynoticeManager.getStdHealthbureauById(id);
					 su.setName(stdHealthbureau.getHeaBurName());
					 su.setPhone(stdHealthbureau.getContactTelephone());
					break;
				default:
					su=null;
					break;
				}
				if(userManager.addSysUser(su)){//保存主账号成功
					String zhuRole=SysRoleType.getSysRoleType(userType).getValue();
					userManager.addSysUserRoleAndPrivilege(su.getId(),zhuRole,now,createUserId);
					page.getConditions().put("zhuUserName", su.getUsername());
					page.getConditions().put("zhuPassword", password);
					page.getConditions().put("url", url);
					if(generateSubAccount!=null && generateSubAccount==1){//生成子账户
						List<SysRole> sysRoles = userManager.getSysRoleListByType(zhuRole);
						if( sysRoles!=null && sysRoles.size()>0 ){
							for(SysRole sr:sysRoles){
								SysUser  subSu= new SysUser();
								BeanCopierUtils.copyProperties(su, subSu);
								String subUserName = AccountUtil.getSubSequence(zhuSequence);
								String subPassword = AccountUtil.getPassword(6);
								subSu.setId(UUID.randomUUID().toString());
								subSu.setUsername(subUserName);
								subSu.setPassword(DigestUtils.md5Hex(subPassword));
								subSu.setMain(Whether.no.getKey());
								subSu.setPid(zhuId);
								subSu.setCreateUserId(createUserId);
								subSu.setCreateDateTime(now);
								userManager.addSysUser(subSu);
								userManager.addSysUserRoleAndPrivilege(subSu.getId(),sr.getId(),now,createUserId);
								HashMap<String,String> subMap = new HashMap<String,String>();
								subMap.put("name",sr.getName());
								subMap.put("userName",subSu.getUsername());
								subMap.put("password",subPassword);
								list.add(subMap);
							}
						}
					}
					page.setSuccess(true);
					page.setRows(list);
				}else{
					page.setMsg("生成主账号失败！");
					page.setSuccess(false);
				}
				
			} catch (Exception e) {
				log.error("",e);
				page.setSuccess(false);
			}
			return page;
		}
	}
	/**
	 * @category 中心跳转用户新增编辑页面
	 * @date 2015年6月14日
	 * @return
	 */
	@RequestMapping("/zxUserEdit")
	public String zxUserEdit(Model model, int opType, int userType, String id) {
		log.info("enter zxUserEdit method");
		SysUser user = new SysUser();
		if (opType == 1 && id != null) { // 编辑
			user = userManager.getUserById(id);
			if (user == null) {
				user = new SysUser();
			} else {
				user.setRoleList(roleManager.getRoleListByUser(user));
			}
		} else if (opType == 0 && id != null) { // 新增
			if (UserType.yy.getKey() == userType) { // 新增医疗机构帐户
				HospInfo hospInfo = hospInfoManager.getHospInfoById(id);
				if (hospInfo != null) {
					user.setId(hospInfo.getHospId());
					user.setName(hospInfo.getHospName());
					user.setEmail(hospInfo.getHospInfoDetail()
							.getContactEmail());
					user.setType(userType);
					user.setMain(Whether.yes.getKey());
					user.setPhone(hospInfo.getHospInfoDetail()
							.getContactHandphone());
					user.setStatus(hospInfo.getStatus());
					user.setLocked(Whether.no.getKey());
				}
			} else if (UserType.sc.getKey() == userType
					|| UserType.ps.getKey() == userType) { // 新增企业帐户
				List<StdCompinfo> list = compinfoManager
						.queryStdCompinfoById(id);
				if (list != null && !list.isEmpty()) {
					StdCompinfo compInfo = list.get(0);
					if (compInfo != null) {
						user.setId(compInfo.getCompId());
						user.setName(compInfo.getCompName());
						user.setEmail(compInfo.getStdCompinfoDetail()
								.getContactEmail());
						user.setType(userType);
						user.setMain(Whether.yes.getKey());
						user.setPhone(compInfo.getCompPhone());
						user.setStatus((int) compInfo.getStatus());
						user.setLocked(Whether.no.getKey());
					}
				}
			} else if (UserType.zj.getKey() == userType) { // 新增专家帐户
				StdExpert expert = expertManager.getStdExpertById(id);
				if (expert != null) {
					user.setId(expert.getExpertId());
					user.setName(expert.getName());
					user.setEmail(expert.getEmail());
					user.setType(userType);
					user.setMain(Whether.yes.getKey());
					user.setPhone(expert.getHandphone());
					user.setStatus(expert.getStatus());
					user.setLocked(Whether.no.getKey());
				}
			}
			// 生成主帐号
			Long number = userManager.getSequence();
			String sequence = AccountUtil.generate(
					UserType.getUserType(userType), number);
			user.setUsername(sequence);
			// 生成6位密码
			String password = AccountUtil.getPassword(6);
			user.setPassword(password);
			session.setAttribute("password", password);
		}
		List<SysRole> roleList = roleManager.getZxRoleList();
		model.addAttribute("roleList", roleList);
		model.addAttribute("opType", opType);
		model.addAttribute("user", user);
		return "/sys/zxUserEdit";
	}

	/**
	 * @category 中心保存主用户信息
	 * @date 2015年6月18日
	 * @param user
	 * @param privileges
	 * @return
	 */
	@RequestMapping("zxSaveUser")
	@ResponseBody
	public Pagination zxSaveUser(int opType, SysUser user, String privileges) {
		Pagination page = new Pagination();
		try {
			if (user != null) {
				if (opType == Constants.OP_TYPE_EDIT) {
					user.setUpdUser(getUser().getId());
				} else if (opType == Constants.OP_TYPE_ADD) {
					user.setCreateUserId(getUser().getId());
					String password = (String) session.getAttribute("password");
					String encodedPwd = DigestUtils.md5Hex(password);
					user.setPassword(encodedPwd);
				}
				List<SysPrivilege> list = null;
				if (StringUtils.isNotBlank(privileges)) {
					Gson gson = new Gson();
					Type type = new TypeToken<List<SysPrivilege>>() {
					}.getType();
					list = gson.fromJson(privileges, type);
				}
				user.setPid("0");
				user.setMain(Whether.yes.getKey());
				userManager.zxSaveUser(opType, user, list);
				page.setSuccess(true);
			}
		} catch (MSException e) {
			log.error("",e);
			page.setMsg(e.getMsg());
			page.setSuccess(false);
		} catch (Exception e) {
			log.error("",e);
			page.setMsg("保存失败！");
			page.setSuccess(false);
		}
		return page;
	}
	
	/**
	 * @category 中心保存主用户信息（重寫）
	 * @author 应晓川
	 * @date 2015年10月16日11:50:52
	 * @param user
	 * @return
	 */
	@RequestMapping(value={"saveZUser","saveZUserInfo"})
	@ResponseBody
	public Pagination saveZUser( SysUser user) {
		log.info(user.toString());
		Pagination page = new Pagination();
		SysUser su =  getUser();
		try {
			if(user!=null && StringUtils.isNotBlank(user.getId())){
				userManager.saveZUser(user,su.getId());
				SysUser newuser = (SysUser)session.getAttribute(Constants.USERINFO);
				if(StringUtils.isNotBlank(user.getName())){
					newuser.setName(user.getName());
				}
				if(StringUtils.isNotBlank(user.getName())){
					newuser.setEmail(user.getEmail());	
				}
				if(StringUtils.isNotBlank(user.getName())){
					newuser.setPhone(user.getPhone());
				}
				if(StringUtils.isNotBlank(user.getName())){
					newuser.setRemark(user.getRemark());
				}
				session.setAttribute(Constants.USERINFO, newuser);
				page.setSuccess(true);
				if(StringUtils.isNotBlank(user.getName())){
					su.setName(user.getName());
				}
				if(StringUtils.isNotBlank(user.getEmail())){
					su.setEmail(user.getEmail());
				}
				if(StringUtils.isNotBlank(user.getPhone())){
					su.setPhone(user.getPhone());
				}
				if(StringUtils.isNotBlank(user.getRemark())){
					su.setRemark(user.getRemark());
				}
			}
		}catch (Exception e) {
			log.error("",e);
			page.setMsg("保存失败！");
			page.setSuccess(false);
		}
		return page;
		}
	
	
	@RequestMapping("/addZUser")
	@ResponseBody
	public Pagination addZUser( SysUser user) {
		log.info(user.toString());
		Pagination page = new Pagination();
		if(null != user){
			try {
				userManager.addZUser(user);
				page.setSuccess(true);
			} catch (Exception e) {
				page.setSuccess(false);
			}
		}
		return page;
	}
	
	
	/**
	 * @category 中心、医疗机构、企业子用户管理列表页面
	 * @author 应晓川
	 * @date 2015年6月18日
	 * @param model
	 * @return
	 */
	@RequestMapping("/subUserList")
	public String subUserList(Model model) {
		log.info("enter subUserList method");
		List<Object> roleList = roleManager.getSubRoleListByType(SysRoleType.getSysRoleType(getUser().getType()).getValue(),getUser().getOrgId());
		model.addAttribute("roleList", roleList);
		return "/sys/subUserList";
	}

	/**
	 * @category 中心、医疗机构、企业查询子用户列表
	 * @date 2015年6月18日
	 * @param user
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/getSubUserList")
	@ResponseBody
	public Pagination getSubUserList(SysUser user) {
		log.info(user.toString());
		Pagination page = new Pagination(request);
		try {
			userManager.getSubUserList(page, getUser(), user);
			List<SysUser> list = (List<SysUser>) page.getRows();
			if (list != null && !list.isEmpty()) {
				for (SysUser su : list) {
					su.setRoleList(roleManager.getRoleListByUser(su));
				}
			}
			page.setSuccess(true);
		} catch (Exception e) {
			log.error("",e);
			page.setSuccess(false);
		}
		return page;
	}

	/**
	 * @category 中心、医疗机构、企业子用户新增编辑页面
	 * @date 2015年6月18日
	 * @param model
	 * @return
	 */
	@RequestMapping("/subUserEdit")
	public String subUserEdit(Model model, int opType, String id) {
		log.info("enter subUserList method");
		SysUser user = new SysUser();
		if (opType == Constants.OP_TYPE_EDIT && StringUtils.isNotBlank(id)) {
			user = userManager.getUserById(id);
			Pagination page = new Pagination();
			page.setRows(user);
			if (user == null) {
				user = new SysUser();
			} else {
				user.setRoleList(roleManager.getRoleListByUser(user));
			}
		} else {
			// 生成主帐号
			Long number = userManager.getSequence();
			String sequence = AccountUtil.generate(
					UserType.getUserType(getUser().getType()), number);
			user.setUsername(sequence);
			// 生成6位密码
			String password = AccountUtil.getPassword(6);
			user.setPassword(password);
			session.setAttribute("password", password);
		}
		List<SysRole> roleList = roleManager.getSubRoleList(getUser());
		model.addAttribute("opType", opType);
		model.addAttribute("user", user);
		model.addAttribute("roleList", roleList);
		return "/sys/subUserEdit";
	}
	
	/**
	 * @category 根据id查询用户
	 * @author 韩守松
	 * @date   2015年10月15日
	 * @param  @return
	 */
	@RequestMapping("/subUserDivEdit")
	@ResponseBody
	public Pagination subUserDivEdit(int opType, String id){
		log.info("enter subUserList method");
		Pagination page = new Pagination(request);
		SysUser user = new SysUser();
		if (opType == Constants.OP_TYPE_EDIT && StringUtils.isNotBlank(id)) {
			user = userManager.getUserById(id);
			List<SysRole> roleList = roleManager.getSubRoleList(getUser());
			user.setRole(roleList.get(0));
			page.setSuccess(true);
			page.setRows(user);
		}
		return page;
	}
	

	/**
	 * @category 中心、医疗机构、企业子保存子用户信息
	 * @author 应晓川
	 * @date 2015年6月18日
	 * @param user
	 * @param privileges
	 * @return
	 */
	@RequestMapping(value={"subSaveUser","subEditUser"})
	@ResponseBody
	public Pagination subSaveUser(SysUser subUser,String roleId) {
		log.info(subUser.toString()+"roleId="+roleId);
		Pagination page = new Pagination();
		SysUser  zhuSu= getUser();
		try {
			String subId= subUser.getId();
			SysUser su = new SysUser();
			boolean addTag =false;
			if(StringUtils.isNotBlank(subId)){//存在id则为更新子用户
				su = userManager.getUserById(subId);
				userManager.saveZUser(subUser,zhuSu.getId());
				
			}else{//新增子用户
				//zhuSu
				su.setName(subUser.getName());
				su.setEmail(subUser.getEmail());
				su.setPhone(subUser.getPhone());
				su.setRemark(subUser.getRemark());
				su.setId(UUID.randomUUID().toString());
				su.setOrgId(zhuSu.getOrgId());
				su.setUsername(AccountUtil.getSubSequence(zhuSu.getUsername()));
				String psr = AccountUtil.getPassword(6);
				su.setPassword(DigestUtils.md5Hex(psr));
				su.setAcctEnabled(Whether.yes.getKey());
				su.setLocked(Whether.no.getKey());
				su.setType(zhuSu.getType());
				su.setMain(Whether.no.getKey());
				su.setPid(zhuSu.getId());
				su.setStatus(Whether.yes.getKey());
				su.setCreateUserId(zhuSu.getId());
				su.setCreateDateTime(new Date());
				userManager.addSysUser(su);
				page.getConditions().put("username", su.getUsername());
				page.getConditions().put("password", psr);
				addTag=true;
			}
			if(StringUtils.isNotBlank(roleId)){
				Date now =new Date();
				userManager.addSysUserRoleAndPrivilege(su.getId(),roleId,now,zhuSu.getId());
				if(addTag){
					SysRole sr = roleManager.getRoleById(roleId);
					page.getConditions().put("role",sr.getName());
				}
				page.setSuccess(true);
			}else{
				page.setMsg("请选择用户角色！");
				page.setSuccess(false);
			}
		} catch (Exception e) {
			log.error("",e);
			page.setMsg("保存失败！");
			page.setSuccess(false);
		}
		return page;
	}

	/**
	 * @category 跳转帐号信息打印页面
	 * @date 2015年6月19日
	 * @param model
	 * @param id
	 * @return
	 */
	@RequestMapping("/printUserInfo")
	public String printUserInfo(Model model, String id, String backUrl) {
		log.info("enter printUserInfo method");
		SysUser user = new SysUser();
		if (StringUtils.isNotBlank(id)) {
			user = userManager.getUserById(id);
			String password = (String) session.getAttribute("password");
			if (user != null) {
				user.setPassword(password);
			}
		}
		model.addAttribute("user", user);
		model.addAttribute("backUrl", backUrl);
		return "/sys/printUserInfo";
	}

	/**
	 * @category 中心修改主用户密码
	 * @date 2015年6月19日
	 * @param model
	 * @param id
	 * @return
	 */
	@RequestMapping("/changePassword")
	@ResponseBody
	public Pagination changePassword(Model model, String id, String password) {
		log.info("enter printUserInfo method");
		Pagination page = new Pagination();
		try {
			if (StringUtils.isNotBlank(id) && StringUtils.isNotBlank(password)) {
				String encodedPwd = DigestUtils.md5Hex(password);
				userManager.changePassword(id, encodedPwd);
				page.setSuccess(true);
			}
		} catch (Exception e) {
			log.error("",e);
			page.setSuccess(false);
		}
		return page;
	}

	
	/**
	 * @category 获取未生成主账号的医疗机构
	 * @author 应晓川
	 * @date 2015年10月17日15:53:44
	 * @return page
	 */
	@RequestMapping("/getHospInfoList")
	@ResponseBody
	public Pagination getHospInfoList() {
		log.info("enter getHospInfoList method");
		Pagination page = new Pagination(request);
		try {
			DbUtil.jsonToMap(request, page);
			if(StringUtils.isNotBlank(page.getConditions().get("area1"))){
				String areaId = AreaUtil.getAreaStartCode(page.getConditions().get("area1"),page.getConditions().get("area2"),page.getConditions().get("area3"));
				page.getConditions().remove("area1");
				page.getConditions().remove("area2");
				page.getConditions().remove("area3");
				page.getConditions().put("areaId", areaId);
			}
			userManager.getHospInfoList(page);
			page.setSuccess(true);
		} catch (Exception e) {
			log.error("",e);
			page.setSuccess(false);
		}
		return page;
	}
	
	/**
	 * @category 获取未生成主账号的企业
	 * @author 应晓川
	 * @date 2015年10月17日16:35:56
	 * @return page
	 */
	@RequestMapping("/getCompInfoList")
	@ResponseBody
	public Pagination getCompInfoList() {
		log.info("enter getCompInfoList method");
		Pagination page = new Pagination(request);
		try {
			DbUtil.jsonToMap(request, page);
			if(StringUtils.isNotBlank(page.getConditions().get("area1"))){
				String areaId = AreaUtil.getAreaStartCode(page.getConditions().get("area1"),page.getConditions().get("area2"),page.getConditions().get("area3"));
				page.getConditions().remove("area1");
				page.getConditions().remove("area2");
				page.getConditions().remove("area3");
				page.getConditions().put("areaId", areaId);
			}
			userManager.getCompInfoList(page);
			page.setSuccess(true);
		} catch (Exception e) {
			log.error("",e);
			page.setSuccess(false);
		}
		return page;
	}
	
	/**
	 * @category 获取未生成主账号的专家
	 * @author 应晓川
	 * @date 2015年11月2日12:44:13
	 * @return page
	 */
	@RequestMapping("/getExpertList")
	@ResponseBody
	public Pagination getExpertList() {
		log.info("enter getExpertList method");
		Pagination page = new Pagination(request);
		try {
			DbUtil.jsonToMap(request, page);
			userManager.getStdExpertList(page);
			page.setSuccess(true);
		} catch (Exception e) {
			log.error("",e);
			page.setSuccess(false);
		}
		return page;
	}
	
	
	/**
	 * @category 获取未生成主账号的卫生局
	 * @author 应晓川
	 * @date 2015年10月20日09:41:39
	 * @return page
	 */
	@RequestMapping("/getHeaBurList")
	@ResponseBody
	public Pagination getHeaBurList() {
		log.info("enter getHeaBurList method");
		Pagination page = new Pagination(request);
		try {
			DbUtil.jsonToMap(request, page);
			if(StringUtils.isNotBlank(page.getConditions().get("area1"))){
				String areaId = AreaUtil.getAreaStartCode(page.getConditions().get("area1"),page.getConditions().get("area2"),page.getConditions().get("area3"));
				page.getConditions().remove("area1");
				page.getConditions().remove("area2");
				page.getConditions().remove("area3");
				page.getConditions().put("areaId", areaId);
			}
			userManager.getStdHealthbureauList(page);
			page.setSuccess(true);
		} catch (Exception e) {
			log.error("",e);
			page.setSuccess(false);
		}
		return page;
	}
	
	
	
	/**
	 * @category 医疗机构、生产企业、配送企业、专家、卫生局生成账号弹窗
	 * @date 2015年10月29日15:54:18
	 * @return
	 * @throws UnsupportedEncodingException 
	 */
	@RequestMapping("/toSubAccount")
	public String toSubAccount(Model model,String name,String psr,String roleName) throws UnsupportedEncodingException {
		
		roleName = URLDecoder.decode(roleName,"UTF-8");
		name = URLDecoder.decode(name,"UTF-8");
		log.info("name="+name+",psr="+psr+",roleName="+roleName);
		model.addAttribute("url", url);
		model.addAttribute("name", name);
		model.addAttribute("psr", psr);
		model.addAttribute("roleName", roleName);
		return "/sys/subAccount";
	}
	
	/**
	 * @category 查询所有用户信息
	 * @author 韩守松
	 * @date   2015年11月11日
	 * @param  @param user
	 * @param  @return
	 */
	@RequestMapping("/getAllZxUserList")
	@ResponseBody
	public Pagination getAllZxUserList(SysUser user) {
		log.info(user.toString());
		Pagination page = new Pagination(request);
		try {
			DbUtil.jsonToMap(request, page);
			userManager.getAllZxUserList(page, user);
			page.setSuccess(true);
		} catch (Exception e) {
			log.error("",e);
			page.setSuccess(false);
		}
		return page;
	}
	
	
	public Pagination getYYUserName(String id,Integer userType,String bussinessShow){
		Pagination page = new Pagination();
		List<HashMap<String,String>> list = new ArrayList<HashMap<String,String>>();
		HashMap<String,String> subMap = new HashMap<String,String>();
		/*
		 * 采购主用户
		 */
		SysUser  caiGousu= new SysUser();
		String cgyzhuId = UUID.randomUUID().toString();
		String createUserId = getUser().getId();
		Date  now= new Date();
		String zhuSequence = AccountUtil.getSequence(userType);//主用户账号
		String caiGouzhuSequence = zhuSequence + "-02";//采购员主用户账号
		String caiGoupassword = AccountUtil.getPassword(6);//采购员主用户密码
		caiGousu.setId(cgyzhuId);
		caiGousu.setOrgId(id);
		caiGousu.setUsername(caiGouzhuSequence);
		caiGousu.setPassword(DigestUtils.md5Hex(caiGoupassword));
		caiGousu.setAcctEnabled(Whether.yes.getKey());//激活账号
		caiGousu.setLocked(Whether.no.getKey());//不锁定账号
		caiGousu.setType(userType);//用户类型
		caiGousu.setMain(Whether.yes.getKey());//主账号
		if(StringUtils.isNotBlank(bussinessShow)){
			caiGousu.setBussinessShow(bussinessShow);//账号类型
		}
		caiGousu.setStatus(Whether.yes.getKey());
		caiGousu.setCreateUserId(createUserId);
		caiGousu.setCreateDateTime(now);
		HospInfo newHosp = stdHospInfoManager.getHospInfoById(id);
		String cgyzhuRole=SysRoleType.cgy.getValue();
		SysRole role = userManager.getSysRoleByRoleId(cgyzhuRole);
		caiGousu.setName(newHosp.getHospName()+role.getName());
		if(userManager.addSysUser(caiGousu)){//保存主账号成功
			userManager.addHospAddress(cgyzhuId, createUserId);
			userManager.addSysUserRoleAndPrivilege(caiGousu.getId(),cgyzhuRole,now,createUserId);
			subMap.put("name", role.getName());
			subMap.put("userName", caiGousu.getUsername());
			subMap.put("password", caiGoupassword);
			page.getConditions().put("url", url);
			page.getConditions().put("userType", SysRoleType.yy.getKey()+"");
			list.add(0,subMap);
		}else{
			page.setMsg("生成医院采购员主账号失败！");
			page.setSuccess(false);
		}
		/*
		 * 审核主用户
		 */
		HashMap<String,String> shsubMap = new HashMap<String,String>();
		SysUser  shenHesu= new SysUser();
		String shenHezhuSequence = zhuSequence + "-01";//审核员主用户账号
		String shenHepassword = AccountUtil.getPassword(6);//审核员主用户密码
		String shyzhuId = UUID.randomUUID().toString();
		shenHesu.setId(shyzhuId);
		shenHesu.setOrgId(id);
		shenHesu.setUsername(shenHezhuSequence);
		shenHesu.setPassword(DigestUtils.md5Hex(shenHepassword));
		shenHesu.setAcctEnabled(Whether.yes.getKey());//激活账号
		shenHesu.setLocked(Whether.no.getKey());//不锁定账号
		shenHesu.setType(userType);//用户类型
		shenHesu.setMain(Whether.yes.getKey());//主账号
		if(StringUtils.isNotBlank(bussinessShow)){
			shenHesu.setBussinessShow(bussinessShow);//账号类型
		}
		shenHesu.setStatus(Whether.yes.getKey());
		shenHesu.setCreateUserId(createUserId);
		shenHesu.setCreateDateTime(now);
		String shyzhuRole=SysRoleType.shy.getValue();
		SysRole sysRoles = new SysRole();
		sysRoles = userManager.getSysRoleByRoleId(shyzhuRole);
		shenHesu.setName(newHosp.getHospName()+sysRoles.getName());
		if(userManager.addSysUser(shenHesu)){//保存主账号成功
			userManager.addSysUserRoleAndPrivilege(shenHesu.getId(),shyzhuRole,now,createUserId);
			shsubMap.put("name", sysRoles.getName());
			shsubMap.put("userName", shenHesu.getUsername());
			shsubMap.put("password", shenHepassword);
			list.add(1,shsubMap);
		}else{
			page.setMsg("生成医院审核员主账号失败！");
			page.setSuccess(false);
		}
//		bidProjAreaManager.saveProjHospBuArea(newHosp, getUser());
		page.setSuccess(true);
		page.setRows(list);
		return page;
	}
	@RequestMapping("/toUserRoleManage")
	public String toUserRoleManage(){
		request.setAttribute("userId", request.getParameter("userId"));
		return "/sys/userRoleManage";
	}
	
	@RequestMapping("/saveUserRole")
	@ResponseBody
	public Pagination saveUserRole(String array){
		Pagination page = new Pagination();
		String userId = request.getParameter("userId");
		try {
			if (array != null && !"".equals(array)) {
				Gson gson = new Gson();
				Type type = new TypeToken<List<SysRole>>() {
				}.getType();
				List<SysRole> list = gson.fromJson(array, type);
				if (list != null && list.size()>0) {
					List<String> plist = new ArrayList<String>();
					for (int i = 0; i < list.size(); i++){
						plist.add(list.get(i).getId());
					}
					userManager.saveUserRole(plist, userId);
					page.setSuccess(true);
				}
			}
		} catch (Exception e) {
			page.setSuccess(false);
		}
		return page;
	}
	
	@RequestMapping("/deleteUser")
	@ResponseBody
	public Pagination deleteUser(String array){
		Pagination page = new Pagination();
		try {
			if (array != null && !"".equals(array)) {
				Gson gson = new Gson();
				Type type = new TypeToken<List<SysUser>>() {
				}.getType();
				List<SysUser> list = gson.fromJson(array, type);
				if (list != null && list.size()>0) {
					List<String> plist = new ArrayList<String>();
					for (int i = 0; i < list.size(); i++){
						plist.add(list.get(i).getId());
					}
					userManager.deleteUser(plist);
					page.setSuccess(true);
				}
			}
		} catch (Exception e) {
			page.setSuccess(false);
		}
		return page;
	}
	
	
	
}
